﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace QQ2564874169.Core.ORM.Sqlserver
{
    public class Mssql : BaseSql
    {
        private static string CreateConnectString(string host, string database, string user, string pwd)
        {
            if (host.Contains(":"))
            {
                var items = host.Split(':');
                if (items.Length != 2 || int.TryParse(items[1], out _) == false)
                {
                    throw new FormatException($"host格式不正确：{host}");
                }

                host = host.Replace(":", ",");
            }

            return
                $"Data Source={host};Initial Catalog={database};Integrated Security=false;User ID={user};Password={pwd}";
        }

        public Mssql(string host, string database, string user, string pwd)
            : this(CreateConnectString(host, database, user, pwd))
        {

        }

        public Mssql(string connectString) : base(new SqlConnection(connectString))
        {

        }

        protected override IDbDataParameter ToParam(string name, object value)
        {
            return new SqlParameter(name, value);
        }

        protected override string ToPageSql(string src, PageSet page)
        {
            var countSql = $"SELECT COUNT(1) FROM({src}) T";
            var orderSql = "";
            if (page.Sorts.Count > 0)
            {
                page.Check();
                orderSql = "ORDER BY";
                foreach (var item in page.Sorts)
                {
                    if (item.StartsWith("!"))
                    {
                        orderSql += " " + item.Substring(1) + " DESC";
                    }
                    else
                    {
                        orderSql += " " + item + " ASC";
                    }
                }

                orderSql = $" OVER({orderSql})";
            }
            var start = (page.Index - 1) * page.Count;
            var end = start + page.Count + 1;
            var dataSql = $@"SELECT * FROM (
                                SELECT *,ROW_NUMBER(){orderSql} PAGEROW FROM ({src}) T
                            ) T WHERE PAGEROW>{start} AND PAGEROW<{end}";
            return countSql + ";" + dataSql;
        }
    }
}
